package cn.wolfcode.luowowo.website.interceptor;

import cn.wolfcode.luowowo.cache.service.IUserInfoRedisService;
import cn.wolfcode.luowowo.member.domain.UserInfo;
import cn.wolfcode.luowowo.website.annotion.RequireLogin;
import cn.wolfcode.luowowo.website.util.CookieUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 登陆检查
 */
public class CheckLogicInterceptor implements HandlerInterceptor{

    @Reference
    private IUserInfoRedisService userInfoRedisService;
    //登陆检查
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception{
        //获取token
        String token = CookieUtil.getToken(request, response);
        //通过token去redis查当前user对象
        UserInfo user = userInfoRedisService.getRedisUserByToken(token);
        //我们只需要拦截动态请求方法--->动态请求方法对象（HandlerMethod）
        if (handler instanceof HandlerMethod){
            HandlerMethod method = (HandlerMethod) handler;
            //判断改请求方法是否贴有注解
            if(method.hasMethodAnnotation(RequireLogin.class)){
                //如果贴了这个注解就要进行登陆
                if (user == null){
                    response.sendRedirect("/login.html");
                    return false;
                }
            }
        }
      //如果请求方法没有贴这个注解就直接能访问
        //并且让所有的请求都可以共享用户对象信息
        request.getSession().setAttribute("userInfo", user);
        //放行
        return true;
    }
}
